package cn.chiship.framework.business.biz.business.service.impl;

import cn.chiship.framework.business.biz.business.entity.BusinessOrderPaymentRecord;
import cn.chiship.framework.business.biz.business.entity.BusinessOrderPaymentRecordExample;
import cn.chiship.framework.business.biz.business.mapper.BusinessOrderPaymentRecordMapper;
import cn.chiship.framework.business.biz.business.pojo.dto.OrderCreateDto;
import cn.chiship.framework.common.util.CodeGenerationUtil;
import cn.chiship.sdk.cache.vo.CacheUserVO;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.business.biz.business.mapper.BusinessOrderHeaderMapper;
import cn.chiship.framework.business.biz.business.entity.BusinessOrderHeader;
import cn.chiship.framework.business.biz.business.entity.BusinessOrderHeaderExample;
import cn.chiship.framework.business.biz.business.service.BusinessOrderHeaderService;
import cn.chiship.sdk.pay.core.enums.PayEnum;
import cn.chiship.sdk.pay.core.enums.TradeTypeEnum;
import cn.chiship.sdk.pay.core.model.PayParamsModel;
import cn.chiship.sdk.pay.factory.PayFactory;
import cn.chiship.sdk.pay.services.PaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单主表业务接口实现层
 * 2023/3/26
 *
 * @author lijian
 */
@Service
public class BusinessOrderHeaderServiceImpl extends BaseServiceImpl<BusinessOrderHeader, BusinessOrderHeaderExample> implements BusinessOrderHeaderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BusinessOrderHeaderServiceImpl.class);
    @Value("${chiship.pay.wx.v2.notifyUrl}")
    private String wxPayV2NotifyUrl;

    @Value("${chiship.pay.wx.v3.notifyUrl}")
    private String wxPayV3NotifyUrl;

    @Value("${chiship.pay.ali.notifyUrl}")
    private String aliPayNotifyUrl;

    @Value("${chiship.pay.ali.returnUrl}")
    private String aliPayReturnUrl;
    @Resource
    BusinessOrderHeaderMapper businessOrderHeaderMapper;
    @Resource
    BusinessOrderPaymentRecordMapper businessOrderPaymentRecordMapper;

    @Override
    public BaseResult createOrder(OrderCreateDto orderCreateDto, CacheUserVO cacheUserVO) {
        Long begin = 0L;
        String noSuffix = businessOrderHeaderMapper.getNoSuffix();
        if (!StringUtil.isNullOrEmpty(noSuffix)) {
            begin = Long.valueOf(noSuffix);
        }

        BusinessOrderHeader orderHeader = new BusinessOrderHeader();
        orderHeader.setId(CodeGenerationUtil.generateOrderId(begin + 1));
        orderHeader.setGmtCreated(System.currentTimeMillis());
        orderHeader.setGmtModified(System.currentTimeMillis());
        orderHeader.setIsDeleted(Byte.valueOf("0"));
        orderHeader.setOrderName(orderCreateDto.getOrderName());
        orderHeader.setOrderDate(System.currentTimeMillis());
        orderHeader.setOrderStatus(Byte.valueOf("0"));
        orderHeader.setCreatedBy(StringUtil.getString(cacheUserVO.getId()));
        orderHeader.setCreatedName(cacheUserVO.getRealName());
        orderHeader.setUserRealName(cacheUserVO.getRealName());
        orderHeader.setUserPhone(cacheUserVO.getMobile());
        orderHeader.setUserId(StringUtil.getString(cacheUserVO.getId()));
        orderHeader.setGrandTotal(new BigDecimal(orderCreateDto.getPrice()));
        return super.insertSelective(orderHeader);
    }

    @Override
    public BaseResult getOrderStatusByOrderId(String orderId) {
        BusinessOrderHeader orderHeader = businessOrderHeaderMapper.selectByPrimaryKey(orderId);
        if (StringUtil.isNull(orderHeader)) {
            return BaseResult.error("查无订单数据！");
        }
        return BaseResult.ok(orderHeader.getOrderStatus());
    }

    @Override
    public BaseResult generatePayQrCode(String orderId, String payMethod) {
        BusinessOrderHeader orderHeader = businessOrderHeaderMapper.selectByPrimaryKey(orderId);
        if (StringUtil.isNull(orderHeader)) {
            return BaseResult.error("订单不存在!");
        }
        String payReturnUrl = null;
        String payNotifyUrl;
        PayEnum payEnum;
        if ("alipay".equals(payMethod)) {
            payReturnUrl = aliPayReturnUrl;
            payNotifyUrl = aliPayNotifyUrl;
            payEnum = PayEnum.PAY_ZFB;
        } else if ("wxpay_v2".equals(payMethod)) {
            payNotifyUrl = wxPayV2NotifyUrl;
            payEnum = PayEnum.PAY_WX_V2;
        } else if ("wxpay_v3".equals(payMethod)) {
            payNotifyUrl = wxPayV3NotifyUrl;
            payEnum = PayEnum.PAY_WX_V3;
        } else {
            return BaseResult.error("暂不支持的支付方式!");
        }
        PaymentService paymentService = PayFactory.getPaymentService(payEnum);

        PayParamsModel payParamsModel = new PayParamsModel(
                orderId,
                orderHeader.getOrderName(),
                orderHeader.getOrderName(),
                orderHeader.getGrandTotal().doubleValue(),
                payNotifyUrl,
                null
        );
        payParamsModel.setReturnUrl(payReturnUrl);
        BaseResult baseResult = paymentService.doPay(payParamsModel, TradeTypeEnum.QR_CODE);
        return baseResult;
    }

    @Override
    public BaseResult selectDetailsByPrimaryKey(Object id) {
        Map<String, Object> result = new HashMap<>(2);
        BusinessOrderHeader orderHeader = businessOrderHeaderMapper.selectByPrimaryKey(id);
        result.put("orderHeader", orderHeader);
        BusinessOrderPaymentRecordExample businessOrderPaymentRecordExample = new BusinessOrderPaymentRecordExample();
        businessOrderPaymentRecordExample.createCriteria().andOrderIdEqualTo(StringUtil.getString(id));
        List<BusinessOrderPaymentRecord> businessOrderPaymentRecords = businessOrderPaymentRecordMapper.selectByExample(businessOrderPaymentRecordExample);
        BusinessOrderPaymentRecord businessOrderPaymentRecord = new BusinessOrderPaymentRecord();
        if (!businessOrderPaymentRecords.isEmpty()) {
            businessOrderPaymentRecord = businessOrderPaymentRecords.get(0);
        }
        result.put("paymentRecord", businessOrderPaymentRecord);
        return BaseResult.ok(result);
    }
}
